package com.tobeing.picture.picker.activities;

import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tobeing.picture.picker.R;
import com.tobeing.picture.picker.adapters.ImageAdapter;
import com.tobeing.picture.picker.customs.FolderClickListener;
import com.tobeing.picture.picker.customs.FolderWin;
import com.tobeing.picture.picker.models.Folder;
import com.tobeing.picture.picker.models.Image;

import java.io.File;
import java.io.FilenameFilter;
import java.sql.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class MainActivity extends AppCompatActivity {
    private GridView mGVImage;
    private LinearLayout mLLFolder;
    private TextView mTVDirName;
    private TextView mTVImageCount;

    private ImageAdapter mImageAdapter;
    private List<Folder> mFolders = new ArrayList<>();
    private Set<String> mDirs = new HashSet<>();

    private FolderWin mFolderWin;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Folder folder = (Folder) msg.obj;
            String fileName;
            if(TextUtils.isEmpty(folder.getDir())){
                fileName = "全部图片";
            }else {
                File file = new File(folder.getDir());
                fileName = file.getName();
            }
            mTVDirName.setText(fileName);
            mTVImageCount.setText(folder.getImages().size() + "");
            mImageAdapter = new ImageAdapter(MainActivity.this, folder.getImages());
            mGVImage.setAdapter(mImageAdapter);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
        initData();
        initEvents();
    }

    private void initViews() {
        mGVImage = findViewById(R.id.gv_image);
        mLLFolder = findViewById(R.id.ll_folder);
        mTVDirName = findViewById(R.id.tv_dir_name);
        mTVImageCount = findViewById(R.id.tv_image_count);
    }

    private void initData() {
        Folder folder = new Folder();
        mFolders.add(folder);
        queryImages();
    }

    private void initEvents() {
        mLLFolder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mFolderWin == null){
                    mFolderWin = new FolderWin(MainActivity.this, mFolders);
                    mFolderWin.setFolderClickListener(new FolderClickListener() {
                        @Override
                        public void onClick(Folder folder) {
                            Message message = Message.obtain();
                            message.obj = folder;
                            mHandler.sendMessage(message);
                        }
                    });
                }
                mFolderWin.showAsDropDown(mLLFolder, 0, 0);
            }
        });
    }

    private void queryImages() {
        if (!TextUtils.equals(Environment.getExternalStorageState(), Environment.MEDIA_MOUNTED)) {
            Toast.makeText(this, "当前存储不可用", Toast.LENGTH_LONG).show();
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                Uri imageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                ContentResolver cr = getContentResolver();
                Cursor cursor = cr.query(imageUri, null, MediaStore.Images.Media.MIME_TYPE + "=? or " +
                                MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?",
                        new String[]{"image/jpeg", "image/jpg", "image/png"}, MediaStore.Images.Media.DATE_MODIFIED);
                while (cursor.moveToNext()) {
                    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    mFolders.get(0).getImages().add(path);
                    File parentFile = new File(path).getParentFile();
                    if (parentFile == null) {
                        continue;
                    }
                    String dir = parentFile.getAbsolutePath();
                    if(!mDirs.contains(dir)){
                        mDirs.add(dir);
                        Folder folder = new Folder();
                        folder.setDir(dir);
                        folder.getImages().add(path);
                        mFolders.add(folder);
                    }else {
                        for (int i = 0; i < mFolders.size(); i++) {
                            if (TextUtils.equals(mFolders.get(i).getDir(), dir)) {
                                mFolders.get(i).getImages().add(path);
                                continue;
                            }
                        }
                    }
                }
                cursor.close();
                Message message = Message.obtain();
                message.obj = mFolders.get(0);
                mHandler.sendMessage(message);
            }
        }).start();
    }
}
